import { userList } from '@/services/login/login';
import {
  getOnsiteSupportByPage,
  addOnsiteSupport,
  updateOnsiteSupport,
  delOnsiteSupport,
  getOnsiteSupportById,
} from '@/services/sales/onsiteSupport';
import { CloseCircleOutlined } from '@ant-design/icons';
import ProForm, { ProFormSelect, ProFormTextArea } from '@ant-design/pro-form';
import { FooterToolbar, PageHeaderWrapper } from '@ant-design/pro-layout';
import { Card, Col, message, Popover, Row, Switch } from 'antd';

import { ProFormDatePicker, ProFormInstance, ProFormText } from '@ant-design/pro-components';
import { Button, Form } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import { history, useAccess, useLocation, useModel } from 'umi';
import styles from './style.less';

import { afterSalesNeedList } from '@/services/sales/salesNeedInfo';
import FormItem from 'antd/es/form/FormItem';

const onsiteSupportDetail: React.FC<{}> = () => {
  // eslint-disable-next-line react-hooks/rules-of-hooks
  const location = useLocation();
  const [formTitle, setFormTitle] = useState('新建现场支持'); //
  const actionRef = useRef<ActionType>();
  const [form] = Form.useForm();
  // 表格数据
  const [dataSource, setDataSource] = useState<DataSourceType[]>([]);
  const [formDisabled, setFormDisabled] = useState(false); //设置表单禁用
  const [finished, setFinished] = useState(0);
  const [saved, setSaved] = useState(0);
  const [engineerDisabled, setEngineerDisabled] = useState(false); // 设置其他工程师禁用

  // const ischecked = false;
  // eslint-disable-next-line react-hooks/rules-of-hooks
  const { initialState } = useModel('@@initialState');
  const { currentUser } = initialState || {};
  // eslint-disable-next-line react-hooks/rules-of-hooks
  const access = useAccess();
  const [buttonDisabled, setButtonDisabled] = useState(false);
  const [buttonHided, setButtonHided] = useState(false);

  const hiddenSolution = () => {
    return access.canAdmin() || access.canChiefEngineer() ? false : true;
  };

  let user = {};
  console.log(currentUser, '---currentUser---');

  // eslint-disable-next-line react-hooks/rules-of-hooks
  useEffect(() => {
    (async () => {
      if (location.query.id !== undefined && location.query.id !== null) {
        const result = await getOnsiteSupportById({ id: location.query.id });
        setFormDisabled(true);
        user = result?.data?.supportEngineerEx;
        // user = result?.data?.createName;
        setFinished(result?.data?.supportStatus);
        console.log(result?.data?.supportStatus, '---result?.data?.supportStatus---');
        console.log(finished, '---finished---');
        if (access.canEngineer() && result?.data?.supportStatus == 1) {
          setButtonHided(true);
        }
        if (
          access.canChiefEngineer() ||
          result?.data?.supportStatus == 0 ||
          result?.data?.supportStatus == 1
        ) {
          setButtonDisabled(true);
        }
        if (access.canEngineer() && currentUser?.id !== user?.id) {
          setEngineerDisabled(true);
        }
        // console.log(engineerDisabled, "---engineerDisabled---");
        formRef?.current?.setFieldsValue({
          // supportEngineer: { label: user?.name, value: user?.id },
          supportEngineerId: { label: user?.name, value: user?.id },
          supportType: result?.data?.supportType,
          supportDate: result?.data?.supportDate,
          customerName: result?.data?.customerName,
          BDOrSalesName: result?.data?.bdOrSalesName,
          supportArea: result?.data?.supportArea,

          machineName: result?.data?.machineName,
          branch: result?.data?.branch,
          driveType: result?.data?.driveType,

          supportTitle: result?.data?.supportTitle,
          supportQuestion: result?.data?.supportQuestion,
          supportSolution: result?.data?.supportSolution,

          supportSuggestion: result?.data?.supportSuggestion,
          supportComments: result?.data?.supportComments,
        });
      }
    })();
  }, []);

  const formRef = useRef<
    ProFormInstance<{
      name: string;
      company?: string;
      useMode?: string;
    }>
  >();

  const onFinish = async (values: Record<string, any>) => {
    console.log(values);
    try {
      //新增
      let result = null;

      if (!formDisabled) {
        result = await addOnsiteSupport({
          id: values.id,
          onsiteSupportId: values.onsiteSupportId,
          // supportEngineerId: values.supportEngineer.value,
          supportEngineerId: values.supportEngineerId.value,
          supportType: values.supportType,
          supportDate: values.supportDate,
          customerName: values.customerName,
          bdOrSalesName: values.BDOrSalesName,
          supportArea: values.supportArea,

          machineName: values.machineName,
          branch: values.branch,
          driveType: values.driveType,

          supportTitle: values.supportTitle,
          supportQuestion: values.supportQuestion,
          supportSolution: values.supportSolution,
          supportStatus: finished === 2 ? 0 : finished,
          // supportStatus: finished,

          supportSuggestion: values.supportSuggestion,
          supportComments: values.supportComments,
        });
      } else {
        result = await updateOnsiteSupport({
          id: location.query.id,
          onsiteSupportId: values.onsiteSupportId,
          // supportEngineerId: values.supportEngineer.value,
          supportEngineerId: values.supportEngineerId.value,
          supportType: values.supportType,
          supportDate: values.supportDate,
          customerName: values.customerName,
          bdOrSalesName: values.BDOrSalesName,
          supportArea: values.supportArea,

          machineName: values.machineName,
          branch: values.branch,
          driveType: values.driveType,

          supportTitle: values.supportTitle,
          supportQuestion: values.supportQuestion,
          supportSolution: values.supportSolution,
          supportStatus: finished === 2 ? 0 : finished,
          // supportStatus: finished,

          supportSuggestion: values.supportSuggestion,
          supportComments: values.supportComments,
        });
      }

      if (result !== null && result !== undefined) {
        message.success('提交成功');
        history.push({
          pathname: `/engineer/onsiteSupport`,
        });
      }
    } catch {
      //
    }
  };

  const onTempSave = async () => {
    const values = formRef.current?.getFieldFormatValue?.();
    console.log(currentUser?.id, '---currentUser?.id---');
    console.log(values.supportEngineerId.value, '---values.supportEngineerId.value---');
    try {
      //新增
      let result = null;
      debugger;
      if (!formDisabled) {
        result = await addOnsiteSupport({
          id: values.id,
          onsiteSupportId: values.onsiteSupportId,
          // supportEngineerId: values.supportEngineer.value,
          supportEngineerId: values.supportEngineerId.value,
          supportType: values.supportType,
          supportDate: values.supportDate,
          customerName: values.customerName,
          bdOrSalesName: values.BDOrSalesName,
          supportArea: values.supportArea,

          machineName: values.machineName,
          branch: values.branch,
          driveType: values.driveType,

          supportTitle: values.supportTitle,
          supportQuestion: values.supportQuestion,
          supportSolution: values.supportSolution,
          supportStatus: 2,

          supportSuggestion: values.supportSuggestion,
          supportComments: values.supportComments,
        });
      } else {
        result = await updateOnsiteSupport({
          id: location.query.id,
          onsiteSupportId: values.onsiteSupportId,
          // supportEngineerId: values.supportEngineer.value,
          supportEngineerId: values.supportEngineerId.value,
          supportType: values.supportType,
          supportDate: values.supportDate,
          customerName: values.customerName,
          bdOrSalesName: values.BDOrSalesName,
          supportArea: values.supportArea,

          machineName: values.machineName,
          branch: values.branch,
          driveType: values.driveType,

          supportTitle: values.supportTitle,
          supportQuestion: values.supportQuestion,
          supportSolution: values.supportSolution,
          supportStatus: 2,

          supportSuggestion: values.supportSuggestion,
          supportComments: values.supportComments,
        });
      }
      console.log(result + 'rrrrr');
      if (result !== null && result !== undefined) {
        message.success('保存成功');
        history.push({
          pathname: `/engineer/onsiteSupport`,
        });
        setFinished(2);
      }
    } catch {
      //
    }
  };

  // const otherEngineer = location.query.supportEngineer == currentUser?.loginName ? false : true;

  const [error, setError] = useState<ErrorField[]>([]);

  const onFinishFailed = (errorInfo: any) => {
    setError(errorInfo.errorFields);
  };

  const formAdd = location.query.id === null || location.query.id === undefined ? true : false;

  const onChange = (checked: boolean) => {
    console.log(`switch to ${checked}`);
    checked ? setFinished(1) : setFinished(0);
  };

  return (
    <ProForm
      layout="vertical"
      submitter={{
        render: (props, dom) => {
          if (engineerDisabled || buttonHided) {
            return;
            // return (
            //   <FooterToolbar>
            //     {dom}
            //   </FooterToolbar>
            // );
          } else {
            return (
              <FooterToolbar>
                {dom}
                <Button htmlType="button" key="edit" disabled={buttonDisabled} onClick={onTempSave}>
                  保存
                </Button>
              </FooterToolbar>
            );
          }
        },
      }}
      formRef={formRef}
      onFinish={onFinish}
      onFinishFailed={onFinishFailed}
    >
      <PageHeaderWrapper title={false} breadcrumb={undefined}>
        <Card title="基本信息" className={styles.card} bordered={false}>
          <Row gutter={16}>
            <Col lg={6} md={12} sm={24}>
              <ProFormSelect
                initialValue={
                  formAdd
                    ? { label: currentUser?.loginName, value: currentUser?.id }
                    : { label: user.name, value: user.id }
                }
                disabled
                fieldProps={{
                  labelInValue: true,
                  onChange: (val, val2) => {
                    formRef.current?.setFieldsValue({
                      address: val2?.object?.loginName,
                      phone: val2?.object?.phone,
                    });
                    console.log(val, val2);
                  },
                }}
                debounceTime={1000}
                name="supportEngineerId"
                label="支持工程师"
                showSearch
                request={async (para) => {
                  console.log(para, '--para-');
                  const result = await userList({ blurry: para.keyWords });
                  return result.data.map((item) => {
                    return { label: item.name, value: item.id, object: item };
                  });
                }}
              />
            </Col>
            <Col xl={{ span: 6, offset: 2 }} lg={{ span: 8 }} md={{ span: 12 }} sm={24}>
              <ProFormSelect
                fieldProps={{
                  onChange: (val, val2) => {
                    console.log(val, val2);
                  },
                }}
                name="supportType"
                label="支持类型"
                options={[
                  { label: '测试', value: 1 },
                  { label: '拜访', value: 2 },
                ]}
                rules={[
                  {
                    required: true,
                    message: '请输入支持类型',
                  },
                ]}
                disabled={engineerDisabled}
              />
            </Col>
            <Col xl={{ span: 6, offset: 2 }} lg={{ span: 8 }} md={{ span: 12 }} sm={24}>
              <ProFormDatePicker
                label="支持日期"
                name="supportDate"
                rules={[
                  {
                    required: true,
                    message: '请输入支持日期',
                  },
                ]}
                disabled={engineerDisabled}
              />
            </Col>
          </Row>
          <Row gutter={16}>
            <Col lg={6} md={12} sm={24}>
              <ProFormText
                label="客户名称"
                name="customerName"
                rules={[
                  {
                    required: true,
                    message: '请输入客户名称',
                  },
                ]}
                disabled={engineerDisabled}
              />
            </Col>
            <Col xl={{ span: 6, offset: 2 }} lg={{ span: 8 }} md={{ span: 12 }} sm={24}>
              <ProFormText
                label="BD或销售名称"
                name="BDOrSalesName"
                rules={[
                  {
                    required: true,
                    message: '请输入BD或销售名称',
                  },
                ]}
                disabled={engineerDisabled}
              />
            </Col>
            <Col xl={{ span: 6, offset: 2 }} lg={{ span: 8 }} md={{ span: 12 }} sm={24}>
              <ProFormSelect
                fieldProps={{
                  onChange: (val, val2) => {
                    console.log(val, val2);
                  },
                }}
                name="supportArea"
                label="区域"
                options={[
                  { label: 'RC', value: 1 },
                  { label: 'RE', value: 2 },
                  { label: 'RS', value: 3 },
                  { label: 'RW', value: 4 },
                  { label: 'RN', value: 5 },
                  { label: 'RNE', value: 6 },
                ]}
                rules={[
                  {
                    required: true,
                    message: '请输入区域',
                  },
                ]}
                disabled={engineerDisabled}
              />
            </Col>
          </Row>
        </Card>
        <Card title="设备信息" className={styles.card} bordered={false}>
          <Row gutter={16}>
            <Col lg={6} md={12} sm={24}>
              <ProFormText
                label="设备名称"
                name="machineName"
                rules={[
                  {
                    required: true,
                    message: '请输入设备名称',
                  },
                ]}
                disabled={formDisabled}
              />
            </Col>
            <Col xl={{ span: 6, offset: 2 }} lg={{ span: 8 }} md={{ span: 12 }} sm={24}>
              <ProFormSelect
                fieldProps={{
                  onChange: (val, val2) => {
                    console.log(val, val2);
                  },
                }}
                label="行业"
                name="branch"
                options={[
                  { label: '电子', value: 1 },
                  { label: '电池', value: 2 },
                  { label: '物流', value: 3 },
                  { label: '汽车', value: 4 },
                  { label: '太阳能', value: 5 },
                  { label: '增材制造', value: 6 },
                  { label: '包装', value: 7 },
                  { label: '食品饮料', value: 8 },
                  { label: '金属加工', value: 9 },
                  { label: '其他', value: 10 },
                ]}
                rules={[
                  {
                    required: true,
                    message: '请输入行业',
                  },
                ]}
                disabled={engineerDisabled}
              />
            </Col>
            <Col xl={{ span: 6, offset: 2 }} lg={{ span: 8 }} md={{ span: 12 }} sm={24}>
              <ProFormText
                label="驱动类型"
                name="driveType"
                rules={[
                  {
                    required: true,
                    message: '请输入驱动类型',
                  },
                ]}
                disabled={engineerDisabled}
              />
            </Col>
          </Row>
        </Card>
        <Card title="现场支持详情" className={styles.card} bordered={false}>
          <Row gutter={16}>
            <Col lg={{ span: 10 }} md={{ span: 20 }} sm={24}>
              <ProFormTextArea
                label="标题"
                name="supportTitle"
                rules={[
                  {
                    required: true,
                    message: '请输入标题!',
                  },
                ]}
                placeholder="标题"
                fieldProps={{ width: '100%', showCount: true, maxLength: 20, rows: 1 }}
                disabled={engineerDisabled}
              />
            </Col>
          </Row>
          <Row gutter={16}>
            <Col lg={{ span: 22 }} md={{ span: 20 }} sm={24}>
              <ProFormTextArea
                label="问题"
                name="supportQuestion"
                rules={[
                  {
                    required: true,
                    message: '请输入问题!',
                  },
                ]}
                placeholder="问题"
                fieldProps={{ width: '100%', showCount: true, rows: 8 }}
                disabled={engineerDisabled}
              />
            </Col>
          </Row>
          <Row gutter={16}>
            <Col lg={{ span: 22 }} md={{ span: 20 }} sm={24}>
              <ProFormTextArea
                name="supportSolution"
                label="解决方法"
                placeholder="解决方法"
                hidden={false}
                rules={[
                  {
                    required: true,
                    message: '请输入解决方法!',
                  },
                ]}
                disabled={engineerDisabled}
              />
            </Col>
          </Row>

          <Row gutter={16}>
            <Col lg={{ span: 22 }} md={{ span: 20 }} sm={24}>
              <ProFormTextArea
                name="supportSuggestion"
                label="建议"
                placeholder="建议"
                hidden={hiddenSolution() && finished !== 1}
                disabled={hiddenSolution() || engineerDisabled}
              />
            </Col>
          </Row>
          <Row gutter={16}>
            <Col lg={{ span: 22 }} md={{ span: 20 }} sm={24}>
              <ProFormTextArea
                name="supportComments"
                label="备注"
                placeholder="备注"
                hidden={hiddenSolution() && finished !== 1}
                disabled={hiddenSolution()}
              />
            </Col>
          </Row>
          <Row gutter={16}>
            <Col lg={{ span: 22 }} md={{ span: 20 }} sm={24}>
              <FormItem>
                <Switch
                  checked={finished === 1}
                  disabled={hiddenSolution()}
                  checkedChildren="已完成"
                  unCheckedChildren="未完成"
                  onChange={onChange}
                />
              </FormItem>
            </Col>
          </Row>
        </Card>
      </PageHeaderWrapper>
    </ProForm>
  );
};

export default onsiteSupportDetail;
